package org.fjsei.yewu.security;

import md.system.User;
import md.system.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    //参数username identifying the user；改成用户表的ID； spring security只需要以ID识别用户。
    @Override
    @Transactional(timeout = 30) // 30秒超时
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            User user = userRepository.findByUsername(username);

            if (user == null) {
                throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
            } else {
                return JwtUserFactory.create(user);
            }
        } catch (Exception e) {
            throw new UsernameNotFoundException("Database timeout or error: " + e.getMessage());
        }
    }
}
